package com.beiding.test.pg;

import com.beiding.sqlbuilder.ConditionUnit;
import com.beiding.sqlbuilder.ConditionUnitContainer;
import com.beiding.sqlbuilder.ConditionUnitHandler;
import com.beiding.sqlbuilder.ConditionUnitHolder;

import java.util.List;

public class ConditionContainerHandler implements ConditionUnitHandler {

    @Override
    public boolean canHandle(ConditionUnit conditionUnit) {
        return conditionUnit instanceof ConditionUnitContainer;
    }

    @Override
    public String handle(ConditionUnit conditionUnit) {
        ConditionUnitContainer container = (ConditionUnitContainer) conditionUnit;

        List<ConditionUnitHolder> conditionUnits = container.getConditionUnits();

        StringBuilder builder = new StringBuilder();
        for (ConditionUnitHolder unit : conditionUnits) {
            builder.append(unit.execute());
        }

        if (conditionUnits.size() == 1 || !container.isInner()) {
            return builder.toString();
        } else {
            return "(" + builder.toString() + ")";
        }
    }
}
